#pragma once
#include <iostream>
#include <cstdio>
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <signal.h>

using namespace std;

class client
{
public:
    client(const char *ip, uint16_t port)
        : _server_ip(ip), _server_port(port), _sock_fd(-1)
    {
    }

    void client_init()
    {
        // create socket
        _sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sock_fd < 0)
        {
            std::cerr << "create socket error" << errno << strerror(errno) << std::endl;
            exit(0);
        }

        std::cout << "create socket success" << std::endl;

        // 客户端不需要绑定，系统会默认处理
    }

    void client_start()
    {

        bool quit = false;
        std::string message;
        socklen_t to_ser_len = sizeof(_to_server);
        _to_server.sin_addr.s_addr = inet_addr(_server_ip.c_str());
        _to_server.sin_port = htons(_server_port);

        struct sockaddr_in from_server;
        socklen_t from_ser_len = sizeof(from_server);

        std::cout << "你正在使用简易在线翻译" << endl;
        std::cout << "输入 英文单词 即可返回中文意思" << endl;

        while (true)
        {
            std::cout << "please enter word: ";
            std::cin >> message;
            sendto(_sock_fd, message.c_str(), message.size(), 0,
                   (struct sockaddr *)&_to_server, to_ser_len);

            char receive_buff[1024];
            ssize_t size = recvfrom(_sock_fd, receive_buff, sizeof(receive_buff) - 1, 0,
                                    (struct sockaddr *)&from_server, &from_ser_len);

            if (size > 0)
            {
                receive_buff[size] = 0;
                string recv_message = receive_buff;
                std::cout << recv_message << std::endl;
            }
        }
    }

private:
    std::string _server_ip;
    uint16_t _server_port;
    int _sock_fd;
    struct sockaddr_in _to_server;
};